package com.central.oauth.tenant;

import com.central.common.constant.CommonConstant;
import com.central.common.context.TenantContextHolder;
import com.central.oauth.service.IValidateCodeService;
import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 替换 UsernamePasswordAuthenticationFilter 增加租户id
 *
 * @author ly
 */
@Setter
public class TenantUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private boolean postOnly = true;

    public TenantUsernamePasswordAuthenticationFilter() {
        super();
    }

    private IValidateCodeService validateCodeService;

    public TenantUsernamePasswordAuthenticationFilter(IValidateCodeService validateCodeService) {
        super();
        this.validateCodeService = validateCodeService;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals(CommonConstant.REQUEST_METHOD_POST)) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String clientId = TenantContextHolder.getTenant();

        // 获取到验证码
        String validCode = request.getParameter("validCode");
        String deviceId = request.getParameter("deviceId");
        validateCodeService.validate(deviceId, validCode);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        TenantUsernamePasswordAuthenticationToken authRequest = new TenantUsernamePasswordAuthenticationToken(username,
                password, clientId);

        setDetails(request, authRequest);
        // 走 com.central.oauth.service.impl.UserDetailServiceImpl.loadUserByUsername 认证账号密码
        return getAuthenticationManager().authenticate(authRequest);
    }
}
